<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Folder;
use app\api\model\v1\GatherFile;
use app\api\model\v1\Project;
use app\api\model\v1\ProjectDetail;
use app\api\model\v1\ProjectSample;
use app\api\model\v1\ProjectSecondLevel;
use app\api\model\v1\ProjectType;
use app\api\model\v1\WxLog;
use app\BaseController;
use think\facade\Env;
use think\Request;
use think\Response;

class FolderCon extends BaseController
{
    use SearchDataForModel,FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/11/16
     * @Time: 16:28
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 文件夹列表
     */
    public function getFolderList(){
        $limit =  $this->request->param('limit',10);
//        $res = $this->search(new Folder(),[],$limit,'desc',['user','folder','project'],['folder']);
        $res = Folder::withCount(['folder'=>function($query){
            $query->where(['is_allot'=>GatherFile::IS_ALLOT_ONE]);
            return $query;
        }])->with(['user','folder'=>function($q){
            $q->where(['is_allot'=>GatherFile::IS_ALLOT_ONE]);
            return $q;
        },'project'])->order('folder_count desc')->paginate($limit);
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/11/18
     * @Time: 8:32
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 文件列表
     */
    public function getGatherFileList(){
        $limit =  $this->request->param('limit',10);
        $map = [];
        if ($this->request->has('folder_id') && !empty($this->request->param('folder_id'))) {
            $map[] = ['folder_id', '=',$this->request->param('folder_id')];
        }
        if ($this->request->has('is_audit') && !empty($this->request->param('is_audit'))) {
            $map[] = ['is_audit', '=',$this->request->param('is_audit')];
        }
        if ($this->request->has('project_detail_id') && !empty($this->request->param('project_detail_id'))) {
            $map[] = ['project_detail_id', '=',$this->request->param('project_detail_id')];
        }
        $res = $this->search(new GatherFile(),$map,$limit,'desc',['user','project','projectType','projectSample'])->each(function ($item,$key){
            $item['show'] = '';
            return $item;
        });
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/18
     * @Time: 10:29
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取对应的文件夹
     */
    public function getFolderOneInfo(){
        $ids = $this->request->param('ids',0);
        $res = GatherFile::with(['project','projectType'=>['projectSecondLevel'],'projectSample','projectDetail','projectSecond'])->find($ids);
        if (is_null($res)){
            return $this->response(403,'暂未找到该文件夹');
        }
        return $this->response($res->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/18
     * @Time: 10:59
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取详细指标
     */
    public function getProjectDetail(){
        $project_second_level_id = $this->request->param('project_second_level_id');
        $res = ProjectDetail::where(['project_second_level_id'=>$project_second_level_id])->select();
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/18
     * @Time: 15:19
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 采集列表
     */
    public function getProjectGatherFileInfo()
    {
        $project_id = $this->request->param('project_id',9);
        $folder_id= $this->request->param('folder_id',29);
        $is_audit = $this->request->param('is_audit',1);
        $res = ProjectDetail::withCount(['gatherFile'=>function($query) use ($project_id,$folder_id){
            $query->where(['project_id'=>$project_id,'folder_id'=>$folder_id]);
            return $query;
        },'gatherFileYet'=>function($yet)use ($project_id,$folder_id){ //已审核统计
            $yet->where(['project_id'=>$project_id,'folder_id'=>$folder_id,'is_audit'=>GatherFile::IS_AUDIT_TWO]);
            return $yet;
        },'gatherFileNot'=>function($not)use ($project_id,$folder_id){ //未审核统计
            $not->where(['project_id'=>$project_id,'folder_id'=>$folder_id,'is_audit'=>GatherFile::IS_AUDIT_ONE]);
            return $not;
        }])->with(['gatherFile'=>function($query) use ($project_id,$folder_id,$is_audit){
                $query->with(['projectSample','user'])->where(['project_id'=>$project_id,'folder_id'=>$folder_id,'is_audit'=>$is_audit]);
                return $query;
        },'project','projectType','projectSecond'])->where(['project_id'=>$project_id])->select()->each(function ($i,$k){
            if(!empty($i['gatherFile'])){
                foreach ($i['gatherFile'] as $k1=>$v1){
                    $v1['show'] = '';
                }
                return $i;
            }
        })->filter(function (ProjectDetail $projectDetail){
            if (count($projectDetail->gatherFile) >0){
                return true;
            }
        })->toArray();
        if (empty($res)){
            return $this->response(403,'暂无数据');
        }else{
            return $this->response(array_values($res));
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/19
     * @Time: 8:52
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 审核数据
     */
    public function saveAuditResult(){
        $data = $this->request->param();
        $id_arr = explode(',',$data['ids']);
        foreach ($id_arr as $key=>$value){
            $gather = GatherFile::find($value);
            if (is_null($gather)){
                return $this->response(403,'暂未找到该数据');
            }
            $data['is_audit'] = GatherFile::IS_AUDIT_TWO; //已审核
            $gather->save($data);
            AdminLog::record('审核数据', $data, $this->request->uid, $this->request->username);
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/19
     * @Time: 9:08
     * @return \think\response\Json
     * 删除采集信息
     */
    public function delGatherFile(){
        $ids = $this->request->param('ids');
        $ids_arr = explode(',',$ids);
        GatherFile::destroy($ids_arr);
        AdminLog::record('删除数据', $this->request->param(),$this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/19
     * @Time: 10:27
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取项目下面所有的信息
     */
    public function getProjectSelectAll(){
        $project = Project::with(['projectType'])->select()->toArray();
        return $this->response($project);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/19
     * @Time: 11:28
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据项目id获取对应的一级指标及样本点
     */
    public function getProjectIdFolder(){
        $project_id = $this->request->param('project_id');
        $folder = ProjectType::where(['project_id'=>$project_id])->select()->toArray();
        return $this->response($folder);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/19
     * @Time: 14:08
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据一级指标获取对应的样本点
     */
    public function getSampleInfo(){
        $project_type_id = $this->request->param('project_type_id');
        $folder = ProjectSample::where(['project_type_id'=>$project_type_id])->select()->toArray();
        return $this->response($folder);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/19
     * @Time: 14:56
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 移动数据
     */
    public function saveMoveFile(){
        $data = $this->request->param();
        $project_type = ProjectType::find($data['project_type_id']);
        $project_sample = ProjectSample::find($data['project_sample_id']);
        $folder = Folder::where(['project_id'=>$data['project_id'],'project_type_id'=>$data['project_type_id'],'project_sample_id'=>$data['project_sample_id']])->find();
        if (is_null($folder)){
            $folder_id = Folder::create([
                'title'=>$project_type['project_type_name'],
                'sub_title'=>$project_sample['title'],
                'project_id'=>$data['project_id'],
                'project_type_id'=>$data['project_type_id'],
                'project_sample_id'=>$data['project_sample_id']
            ])->id;
        }else{
            $folder_id = $folder['id'];
        }
        $id_arr = explode(',',$data['ids']);
        $data['folder_id'] = $folder_id;
        foreach ($id_arr as $key=>$value){
            $gather = GatherFile::find($value);
            if (is_null($gather)){
                return $this->response(403,'暂未找到该数据');
            }
            $gather->save($data);
            AdminLog::record('移动数据', $data, $this->request->uid, $this->request->username);
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/19
     * @Time: 15:11
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取采集详情
     */
    public function gatherFileDetail(){
        $data = $this->request->param();
        $res = GatherFile::find($data['ids']);
        return $this->response($res->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/24
     * @Time: 16:39
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除文件夹
     */
    public function delFolder(){
        $id = $this->request->param('id');
        $type = $this->request->param('type','pc');
        $folder = Folder::with(['folder'])->find($id);
       if (is_null($folder)){
           return $this->response(403,'暂未找到该文件夹');
       }
        $folder->together(['folder'])->delete();
       if ($type === 'wx'){
           WxLog::record('微信端删除文件夹', $this->request->param(), $this->request->wx_id);
       }else{
           AdminLog::record('PC端删除文件夹', $this->request->param(), $this->request->uid, $this->request->username);
       }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/29
     * @Time: 11:08
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * 导出图片
     */
    public function importImgZip(){
        $id = $this->request->param('id');
        $folder = Folder::with(['folder'])->find($id);

        $file = GatherFile::with(['user','projectDetail'])->field('id,user_id,project_detail_id,url')->limit(10)->select()->toArray();
//        if (is_null($folder)){
//            return $this->response(403,'暂未找到该文件夹');
//        }
//        $str = 'storage/gather_img/20211122/f8d3344e52db3381d9914f53bc5d0957s.png';
//        halt(file_exists($str));
        $env = Env::get('DOMAIN.domain_name', 'DOMAIN.default_domain');

        $dir = 'uploads/zip/';

        if(!file_exists($dir)){
            mkdir($dir,0777,true);
        }
        $homeworkId = 'quality_'.time();
        $zipName = $dir.$homeworkId.'.zip';
        $zip = new \ZipArchive;
        if($zip->open($zipName,\ZipArchive::CREATE|\ZipArchive::OVERWRITE)){
            foreach($file as $key=>$value){
                $img_arr = explode($env,$value['url']);
                $new_img_arr = array_values(array_filter($img_arr));
                $file_ext=explode('.',$new_img_arr[0]);
                $project_title_detail = is_null($value['projectDetail']) ? '暂未分配' : $value['projectDetail']['project_detail_title'];
                $user_name =is_null($value['user']) ? '未匹配到用户' : $value['user']['nickname'];
                if(file_exists($new_img_arr[0])){
                    $zip->addFromString($folder['title'].'/'.$folder['sub_title'].'/'.$project_title_detail.'-'.$user_name.'-'.$key.'.'.$file_ext[1],file_get_contents(trim($value['url'])));
                }
            }
            $zip->close();
            header("Cache-Control: public");
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="ITblog.zip"');
            header('Content-Transfer-Encoding: binary');
            header('Content-Length: ' . filesize($zipName)); //告诉浏览器，文件大小
            readfile($zipName);
            //下载后删除临时目录
            @unlink(app()->getRootPath().'public/'.$zipName);//删除压缩包
        }
    }
}
